#!/usr/bin/env python2

import sys

def taxonomyTree(tidTreePath, tidTree, level):
	# z = {'no rank': 2, 'species':2, 'subspecies':2, 'varietas':2, 'subgenus':2, 'forma':2, 'species subgroup':2, 'species group':2, 'genus':1}	
	z = {'no rank':2 }
	l= ["superkingdom","kingdom","subkingdom","superphylum","phylum","subphylum","superclass","class","subclass","infraclass","superorder","order","parvorder","suborder","infraorder","superfamily","family","subfamily","tribe","subtribe","genus","subgenus","species group","species subgroup","species","subspecies","forma","varietas"]
	
	llength = len(l) 
	level_index = l.index(level)
	
	z[l[level_index]] = 1
	# print z

	i = level_index + 1 
	while i < llength:
		z[l[i]] = 2 
		i = i + 1
	# print za
	norankList = []
	fp = open(tidTreePath)
	for ln in fp:
		lnlist = ln.strip().split('\t|\t')
		if lnlist[2] == 'no rank':
			norankList.append(lnlist[0])
		if lnlist[2] in z:
			tidTree[lnlist[0]] = [lnlist[1], z[lnlist[2]]]
		else:
			tidTree[lnlist[0]] = [lnlist[1], 0];
	# print tidTree	
	#don't forget comment 1
	tidTree['1'] = ['1', 0]
	
	checkNoRank(tidTree, norankList)
	# print tidTree['1380744']
	fp.close()


def checkNoRank(tidTree, norankList):
	# print len(norankList)
	for ele in norankList:
		# print ele
		tid = tidTree[ele][0]
		while tidTree[tid][1] > 1:
			tid = tidTree[tid][0]
		# is up species level
		if tidTree[tid][1] == 0:
			tidTree[ele][1] = 0

def outputMap(tidTree):
	for i in tidTree:
		if tidTree[i][1] > 0:
			print i+"|"+tidTree[i][0]+"|"+"1"
		else:
			print i+"|"+tidTree[i][0]+"|"+"0"
if __name__ == "__main__":
	
	taxonomyTreePath = sys.argv[1]
	level = sys.argv[2]
	tidTree = {}
	
	taxonomyTree(taxonomyTreePath, tidTree, level)
	outputMap(tidTree)

